package com.fly.qrcode.api;

import java.awt.image.BufferedImage;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import com.fly.qrcode.qr.QRCodeUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * QR
 * 
 * @author 00fly
 * @version [版本号, 2021年4月14日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@Api(tags = "二维码API接口")
public class ApiController
{
    @ApiOperation("生成二维码")
    @ApiImplicitParam(name = "content", value = "二维码文本", required = true, example = "乡愁是一棵没有年轮的树,永不老去")
    @PostMapping(value = "/create", produces = MediaType.IMAGE_JPEG_VALUE)
    public void index(String content, HttpServletResponse response)
        throws Exception
    {
        BufferedImage image;
        if (StringUtils.isNotBlank(content))
        {
            Resource resource = new ClassPathResource("img/dog.jpg");
            URL imgURL = resource.getURL();
            image = QRCodeUtil.createImage(content, imgURL, true);
        }
        else
        {
            image = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
        }
        // 输出图象到页面
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
}
